package mylab.commons.web.mvc.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import mylab.base.model.dto.Result;
import mylab.base.model.entity.Entity;
import mylab.starters.mybatis.template.SuperService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.Serializable;
import java.util.List;

/**
 * controller~新增
 *
 * @param <K> 对应的entity的ID
 * @param <E> 对应的entity
 * @param <S> 对应的service
 * @param <D> 对应的dto
 */
public interface InsertController<
        K extends Serializable,
        E extends Entity<K>,
        S extends SuperService<K, E>,
        D>
        extends BaseController<K, E, S> {

    @ApiOperation(value = "新增")
    @ApiOperationSupport(order = 1)
    @PostMapping(value = "/save")
    default Result<K> save(@RequestBody @Validated D saveDTO) {
        E po = fromSaveDTO(saveDTO);
        K id = getService().insert(po);
        return id != null ? Result.newSuccess(id) : Result.newFaild("新增失败");
    }


    @ApiOperation(value = "批量新增")
    @ApiOperationSupport(order = 2)
    @PostMapping(value = "/save/batch")
    default Result<Boolean> save(@RequestBody @Validated List<D> saveDTOS) {
        List<E> pos = Lists.newArrayList();
        saveDTOS.forEach(dto -> pos.add(fromSaveDTO(dto)));
        return Result.newSuccess(getService().saveBatch(pos));
    }

    default E fromSaveDTO(D saveDTO) {
        return dtoToPo(saveDTO);
    }
}
